import pymysql
class Database:
    #构造函数

    port  = 3306
    charset = 'utf8'
    def __init__(self,host='127.0.0.1',user = "root",passwd =None,database=None) -> None:
        #将构造函数参数转换为实例属性
        self.host = host
        self.user = user
        self.passwd = passwd
        self.database = database
        #获取MySQL的链接以及游标对象
        self.conn = conn =pymysql.connect(host=self.host,user=self.user,passwd=self.passwd,database=self.database,port=self.port,charset=self.charset)
        self.cursor = conn.cursor()

    def create(self,sql,condition=None):
        try:
            if condition and len(condition) == 1:
                result = self.cursor.execute(sql, condition)
            else:
                result = self.cursor.executemany(sql, condition)
            self.conn.commit()
            print(f"成功插入{result}行数据")
        except Exception:
            self.conn.rollback()
            print("插入错误，数据回滚")
    def read(self,sql, condition=None, data_lines=None):
        result = self.cursor.execute(sql, condition)
        if not data_lines:
            data = self.cursor.fetchall()
        else:
            data = self.cursor.fetchmany(data_lines)
        print(f"查询出{result}行数据")
        for k in data:
            print(*k)


    def update(self,sql, condition=None):
        try:
            result = self.cursor.execute(sql, condition)
            self.conn.commit()
            print(f"成功更新{result}行数据")
        except Exception:
            self.conn.rollback()
            print("更新错误，数据回滚")

    def delete(self,sql, condition=None):
        try:
            result = self.cursor.execute(sql, condition)
            self.conn.commit()
            print(f"成功删除{result}行数据")
        except Exception:
            self.conn.rollback()
            print("删除错误，数据回滚")
if __name__=="__main__":
    db = Database(passwd="123456",database="python")
    insert ='''
insert into user(id,name,age,gender)
values(%s,%s,%s,%s)
    '''
    db.create(sql=insert,condition=((2,"小花",22,"女"),(3,"小李",15,"女")))
    select = '''
        select * from user where id < %s
    '''
    db.read(sql=select, condition=3)
    update = '''
        update user set name="老刘" where name=%s
    '''
    db.update(sql=update, condition="小花")

    delete = '''
        delete from user where id = %s
    '''
    db.delete(sql=delete, condition=3)

'''
#Python中的异常处理
#将可能出现异常的程序放在try语句块中
try:
    int("hello")#执行可能出现异常的代码
except ValueError as e:
    print(e)
    print("程序错误")
except Exception as e:
    print("程序存在未知错误")
else:
    print("程序正常执行，没有任何错误")
finally:
    print("进程关闭")
'''   

